package com.nhy.bloggers.controller;

import com.nhy.bloggers.configur.Result;
import com.nhy.bloggers.entity.User;
import com.nhy.bloggers.service.UserService;
import com.nhy.bloggers.utils.JWTUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public Result login(HttpServletRequest request, HttpServletResponse response,String username,String password){
        if (!StringUtils.hasLength(username) ||
            !StringUtils.hasLength(password)){
            log.error("username:"+username+",password:"+password);
            return Result.fail(-1, "用户名或密码为空");
        }

        User user = userService.getUserInfo(username);
        if (user==null || !user.getPassword().equals(password)){
            return Result.fail(-1, "用户名或密码错误");
        }

        Map<String, Object> claims = new HashMap<>();
        claims.put("id",user.getId());
        claims.put("username",user.getUserName());
        String token = JWTUtils.genJwt(claims);

        log.info("生成token:" + token);
        return Result.success(token);
    }

    @RequestMapping("/getUserInfo")
    public User getUserInfo(HttpServletRequest request){
        String jwtToken = request.getHeader("user_token");
        Integer userId = JWTUtils.getUserIdFromToken(jwtToken);

        if(userId != null){
            return userService.getUserInfoByBlogId(userId);
        }
        return null;
    }

    @RequestMapping("/getAuthorInfo")
    public Result getAuthorInfo(Integer blogId) {
        if (blogId == null && blogId < 1) {
            return Result.fail(-1, "博客ID不正确");
        }
        //根据博客id, 获取作者相关信息
        User user = userService.getUserInfoByBlogId(blogId);
        return Result.success(user);
    }

}
